<template>
  <div class="wrapLimit clx main">
    <div>
      <div class="transportCapacityRecord">
        <!-- isCarrier {{isCarrier}} -->
        <el-form ref="inputModel" :model="data" class="form-baseinfo">
          <div class="remoteInfo">
            <p class="title">下单基本信息</p>
            <div class="info">
              <el-form-item label="员工姓名：" prop="userName">
                <span>{{ data.userName }}</span>
                <!-- <el-input  readonly v-model="data.userName"></el-input> -->
              </el-form-item>
              <el-form-item label="联系电话：" prop="userMobile">
                <span>{{ data.userMobile }}</span>
                <!-- <el-input readonly v-model="data.userMobile"></el-input> -->
              </el-form-item>
              <el-form-item label="厂区名称：" prop="plantName">
                <span>{{ data.plantName }}</span>
                <!-- <el-input readonly v-model="data.plantName"></el-input> -->
              </el-form-item>
              <el-form-item label="所属部门：" prop="departmentName">
                <span>{{ data.departmentName }}</span>
                <!-- <el-input readonly v-model="data.departmentName"></el-input> -->
              </el-form-item>
              <el-form-item label="订单状态：" prop="waybillStatus">
                <span>{{ data.statusName }}</span>
                <!-- <el-input readonly v-model="data.remark"></el-input> -->
              </el-form-item>
              <el-form-item label="订单编号：" prop="departmentName">
                <span>{{ data.soNo }}</span>
                <!-- <el-input readonly v-model="data.departmentName"></el-input> -->
              </el-form-item>
              <el-form-item label="可送货时间：" prop="waybillStatus">
                <span>{{ data.deliverTime }}</span>
                <!-- <el-date-picker readonly v-model="data.deliverTime" type="date" placeholder="不填默认：不限制时间">
                                </el-date-picker> -->
              </el-form-item>
              <el-form-item label="备注：" prop="waybillStatus">
                <span>{{ data.remark }}</span>
                <!-- <el-input readonly v-model="data.remark"></el-input> -->
              </el-form-item>
            </div>
          </div>
        </el-form>

        <el-form ref="ordersProducts" :inline="true" class="form-baseinfo">
          <div class="remoteInfo">
            <p class="title">产品信息</p>
            <div class="info">
              <LPTablePage
                :show-index="false"
                :show-indexfixed="false"
                index-label="序号"
                :table-data="tableData"
                :table-column="tableColumn"
                :height="tableData.length > 10 ? 500 : tableData.length * 44 + 50"
                :total="total"
                :current-page="currentPage"
                :show-page="false"
                align="center"
              >
                <template slot="couponName" slot-scope="{ row }">
                  <div v-if="row.couponModels.length > 0">
                    <div v-for="(item, index) in row.couponModels" :key="index">
                      <el-link type="primary" @click="goToCouponManage(item.couponId)">{{ item.couponName }}</el-link>
                    </div>
                  </div>
                </template>
                <template slot="couponRecordId" slot-scope="{ row }">
                  <div v-if="row.couponModels.length > 0">
                    <div v-for="(item, index) in row.couponModels" :key="index">
                      <div>{{ item.recordId }}</div>
                    </div>
                  </div>
                </template>
                <template slot="settlementMoney" slot-scope="{ row }">
                  <div v-if="data.status === 4">{{ row.settlementMoney }}</div>
                  <div v-if="!isDetail">{{ Math.round(row.pActualCount * row.pPrice * 100) / 100 }}</div>
                </template>
              </LPTablePage>
            </div>
          </div>

          <div class="remoteInfo">
            <p class="title">产品汇总</p>
            <LPTablePage
              :show-index="false"
              :height="productDetail.length > 10 ? 500 : productDetail.length * 43 + 50"
              :table-data="productDetail"
              :table-column="productDetailColumn"
              :show-page="false"
              align="center"
            >
              <template slot="pName" slot-scope="{ row }">
                <div v-if="row.pName == '合计(数量)' || row.pName == '合计(金额-元)'">
                  <div style="font-weight: bold">{{ row.pName }}</div>
                </div>
                <div v-else>{{ row.pName }}</div>
              </template>
              <template slot="pCount" slot-scope="{ row }">
                <div v-if="row.pName == '合计(数量)' || row.pName == '合计(金额-元)'">
                  <div style="font-weight: bold">{{ row.pCount }}</div>
                </div>
                <div v-else>{{ row.pCount }}</div>
              </template>
            </LPTablePage>
          </div>
        </el-form>

        <el-form ref="ordersProducts" :inline="true" class="form-baseinfo">
          <div class="log">
            <p class="title">操作日志</p>
            <LPTablePage
              :show-index="false"
              :height="logData.length > 10 ? 500 : logData.length * 43 + 50"
              :table-data="logData"
              :table-column="logColumn"
              :show-page="false"
              align="center"
            />
          </div>
        </el-form>

        <div class="form-baseinfo">
          <div class="remoteInfo">
            <p class="title">订单使用优惠券情况</p>
            <LPTablePage
              :show-index="true"
              :show-indexfixed="false"
              index-label="序号"
              :table-data="couponData"
              :table-column="couponColumn"
              :height="couponData.length > 10 ? 500 : couponData.length * 43 + 50"
              :show-page="false"
              align="center"
            >
              <template slot="startTime" slot-scope="{ row }">
                <div>{{ row.startTime + '--' + row.endTime }}</div>
              </template>
            </LPTablePage>
          </div>
          <div class="form-baseinfo remoteInfo">
            <el-button class="button" size="medium" @click="close()">关闭</el-button>
            <el-button v-show="!isDetail" class="button" size="medium" type="primary" @click="Save()">完成</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { finishSettleOrder, getByIdOrderData, getOrderCouponList } from '@/api/LaborProtection/order'
import { closeActiveTag, parseTime } from '@/utils/lpUtils.js'
import { operationLog } from '@/api/LaborProtection/operationLog'
import LPTablePage from '@/components/LPTablePage/index.vue'

export default {
  name: 'RemoteOrderDetail',
  components: { LPTablePage },
  data() {
    return {
      data: {},
      tableData: [],
      tableColumn: [
        { label: '物料类型', prop: 'pClassName' },
        { label: '物料编码', prop: 'pNo' },
        { label: '物料名称', prop: 'pTitle' },
        { label: '单位', prop: 'pUnit' },
        { label: '数量', prop: 'pCount' },
        { label: '单价', prop: 'pPrice' },
        { label: '下单金额', prop: 'pMoney' },
        { label: '员工卡号', prop: 'userCardNo' },
        { label: '员工工号', prop: 'userJobNum' },
        { label: '员工姓名', prop: 'userName' },
        { label: '优惠券名称', prop: 'couponName', width: 180, render: true },
        { label: '发放记录编号', prop: 'couponRecordId', width: 200, render: true },
        { label: '实际结算金额', prop: 'settlementMoney', width: 110, render: true, hideTooLtip: true },
        { label: '实际购买数量', prop: 'pCount', width: 110 }
      ],
      logData: [],
      logColumn: [
        { label: '操作时间', prop: 'createTime' },
        { label: '操作人', prop: 'createName' },
        { label: '操作内容', prop: 'remark' }
      ],
      productDetailColumn: [
        { label: '物料小类', prop: 'pName', render: true },
        { label: '物料明细', prop: 'pTitle' },
        { label: '数量', prop: 'pCount', render: true }
      ],
      couponData: [],
      // 表格字段
      couponColumn: [
        { label: '发放记录编码', prop: 'recordId' },
        { label: '优惠券名称', prop: 'couponName' },
        { label: '优惠券有效期', prop: 'startTime', render: true },
        { label: '优惠券内容', prop: 'materialName' },
        { label: '抵扣数量', prop: 'count' }
      ],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      id: '',
      isDetail: true,
      productDetail: [],
      tableCount: 0,
      totalMoney: 0
    }
  },
  mounted() {
    this.getByIdOrderData()
    this.operationLog()
  },
  methods: {

    goToCouponManage(id) {
      this.$router.push({
        path: '/laborProtection/couponManage',
        query: {
          data: JSON.stringify({
            id: id,
            back: '/remoteOrder/components/detail',
            backData: this.$route.query.data
          })
        }
      })
    },
    operationLog() {
      const params = {
        SourceId: this.id
      }
      operationLog(params).then((res) => {
        this.logData = res.items
      })
      getOrderCouponList(this.id).then((res) => {
        this.couponData = res
      })
    },
    getByIdOrderData() {
      const query = JSON.parse(this.$route.query.data)
      this.id = query.id
      this.isDetail = query.isDetail
      getByIdOrderData(this.id).then((res) => {
        res.deliverTime = parseTime(res.deliverTime, '{y}-{m}-{d}')
        res.ordersProducts.forEach((item) => {
          if (res.status != 4) {
            item.pActualCount = item.pCount
            item.settlementMoney = item.pMoney
          }
          this.totalMoney = this.totalMoney + item.pMoney
          this.tableCount = this.tableCount + item.pCount
        })

        this.data = res
        this.tableData = res.ordersProducts
        if (res.ordersProducts.length == 0) return
        const map = new Map()
        const newArr = []
        for (const obj of res.ordersProducts) {
          if (!map.has(obj.pNo)) {
            map.set(obj.pNo, true)
            newArr.push(obj)
          }
        }
        const productArr = []
        newArr.forEach((item) => {
          console.log(item, 123456)
          let tempData = 0
          res.ordersProducts.forEach((tempItem) => {
            if (item.pNo == tempItem.pNo) {
              tempData = tempData + tempItem.pCount
            }
          })
          productArr.push({
            pName: item.pName,
            pNo: item.pNo,
            pTitle: item.pTitle,
            pCount: tempData
          })
        })
        productArr.push(
          {
            pName: '合计(数量)',
            pNo: null,
            pTitle: null,
            pCount: this.tableCount
          },
          {
            pName: '合计(金额-元)',
            pNo: null,
            pTitle: null,
            pCount: this.totalMoney
          }
        )
        this.productDetail = productArr
        console.log(productArr)
      })
    },
    handleSearchSubmit() {
      this.currentPage = 1
    },
    handleSearchReset() {
      this.handleSearchSubmit()
    },
    handleSizeChange(v) {
      this.pageSize = v
      this.currentPage = 1
    },
    handleCurrentChange(v) {
      this.currentPage = v
    },
    Save() {
      const flag = this.tableData.some((item) => item.settlementMoney == 0 || item.settlementMoney == null)
      const flag1 = this.tableData.some((item) => item.pActualCount == 0 || item.pActualCount == null)
      // if (flag1) {
      //     return this.$message.error("实际购买数量不能为空或者零")
      // }
      // if (flag) {
      //     return this.$message.error("实际结算金额不能为空或者零")
      // }

      const ordersProducts = []
      this.tableData.forEach((item) => {
        ordersProducts.push({
          id: item.id,
          pNo: item.pNo,
          pActualCount: item.pActualCount,
          settlementMoney: item.settlementMoney,
          ordersId: item.ordersId
        })
      })
      const data = {
        id: this.data.id,
        ordersProducts: ordersProducts
      }
      finishSettleOrder(data).then((res) => {
        this.$message.success('操作完成')
        this.close()
      })
    },
    close() {
      const query = JSON.parse(this.$route.query.data)
      if (typeof query.lType !== 'undefined') {
        if (query.lType == 1) {
          return closeActiveTag(this, '/laborProtection/order/salesFlow')
        } else {
          return closeActiveTag(this, '/laborProtection/inventoryControl/flowRecord/index')
        }
      }
      if (typeof query.returnOrderId !== 'undefined') {
        // 判断是从退货审核页跳转的还是退货管理页跳转的
        if (typeof query.returnExamine !== 'undefined') {
          // closeActiveTag(this, '/returnOrderManage/detail')
          this.$router.push({
            path: '/laborProtection/order/returnOrderManage/detail',
            query: {
              data: JSON.stringify({
                id: query.returnOrderId,
                isAudit: false
              })
            }
          })
        } else {
          this.$router.push({
            path: '/laborProtection/order/returnOrderManage/orderExamine/detail',
            query: {
              data: JSON.stringify({
                id: query.returnOrderId,
                isAudit: false
              })
            }
          })
          // closeActiveTag(this, '/returnOrderManage/orderExamine/detail')
        }
      } else {
        closeActiveTag(this, '/laborProtection/order/remoteOrder')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.transportCapacityRecord {
  height: 1400px;
  .form-baseinfo {
    margin: 0 45px;
    ::v-deep .el-divider {
      margin-top: 10px;
    }

    .title {
      font-size: 16px;
      font-weight: 550;
    }
  }

  ::v-deep .el-form-item__label {
    text-align: left;
    font-weight: normal;
    color: #666666;
    line-height: 12px;
  }

  ::v-deep .el-form-item__content {
    line-height: 12px;
  }
}
::v-deep .el-form-item {
  height: 40px;
  margin-bottom: 2px;
}

.remark {
  ::v-deep .el-input__inner {
    height: 90px;
  }
}
.remoteInfo {
  .info {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-items: center;
    // margin: 0 45px;
    // border-bottom: 1px solid #ededed;

    .el-form-item {
      width: calc(33%);
      height: 40px;
    }
  }
  .divide {
    width: 100%;
    margin-top: 30px;
  }
}
.collect {
  display: block;
  padding-left: 20px;
  width: 100%;
  height: 40px;
  line-height: 40px;
  background-color: #f2f3f5;
}
.title {
  margin-left: 10px;
  padding: 20px 0 20px 0;
  font-size: 18px;
  &::before {
    content: '';
    display: inline-block;
    width: 3px;
    height: 16px;
    position: absolute;
    left: 45px;
    background: #0076ff;
  }
}

.log {
  .title {
    padding-bottom: 30px;
  }
}

.remoteInfo {
  .button {
    width: 100px;
    position: relative;
    left: 45%;
    top: 30px;
    margin: 0 40px;
    transform: translate(-50%);

    &:nth-of-type(1) {
      color: #333333;
      background-color: #fff;
    }
  }
}
</style>
